package edu.city.class_2201_sno_202212008.Adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.AsyncListDiffer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import edu.city.class_2201_sno_202212008.Domain.UserModel;
import edu.city.class_2201_sno_202212008.R;
import edu.city.class_2201_sno_202212008.databinding.ViewholderLeaderBinding;


public class LeaderAdapter extends RecyclerView.Adapter<LeaderAdapter.ViewHolder> {
    private ViewholderLeaderBinding binding;
    private final AsyncListDiffer<UserModel> differ = new AsyncListDiffer<>(this, new DiffUtil.ItemCallback<UserModel>() {
        @Override
        public boolean areItemsTheSame(@NonNull UserModel oldItem, @NonNull UserModel newItem) {
            return oldItem.getId() == newItem.getId();
        }
        @Override
        public boolean areContentsTheSame(@NonNull UserModel oldItem, @NonNull UserModel newItem) {
            return oldItem.equals(newItem);
        }
    });

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        binding = ViewholderLeaderBinding.inflate(inflater, parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ViewholderLeaderBinding binding = holder.binding;
        UserModel user = differ.getCurrentList().get(position);
        binding.titleTxt.setText(user.getName());
        int drawableResourceId = binding.getRoot().getResources().getIdentifier(
                user.getPic(), "drawable", binding.getRoot().getContext().getPackageName()
        );
        if (drawableResourceId != 0) {
            Glide.with(binding.getRoot().getContext())
                .load(drawableResourceId)
                .into(binding.pic);
        } else {
            binding.pic.setImageResource(R.drawable.ic_launcher_background); // 可换成你的默认头像资源
        }
        binding.rowTxt.setText(String.valueOf(position + 4));
        binding.scoreTxt.setText(String.valueOf(user.getScore()));
    }

    @Override
    public int getItemCount() {
        return differ.getCurrentList().size();
    }

    public AsyncListDiffer<UserModel> getDiffer() {
        return differ;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        ViewholderLeaderBinding binding;
        public ViewHolder(ViewholderLeaderBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
} 